﻿using DryIoc;
using Newtonsoft.Json;
using Prism.Commands;
using Prism.Events;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZoneLineNew.Models.Entity.Template;
using ZoneLineNew.Services.DB;
using ZoneLineNew.Services.Message;
using ZoneLineNew.ViewModelBase;
using ZoneLineNew.Views.Dialogs;

namespace ZoneLineNew.ViewModels {
    public class ViewTableViewModel : NavigationViewModel {

        public ViewTableViewModel(
            IRegionManager regionManager, 
            IDialogService dialog,
            IMessageService messageBox, 
            IEventAggregator eventAggregator, 
            IDbOperate<IFreeSqlMainContext> dbOperate) 
            : base(regionManager, dialog, messageBox, eventAggregator, dbOperate) {



        }


        private string _searchViewTabNameText;

        public string SearchViewTabNameText {
            get { return _searchViewTabNameText; }
            set { _searchViewTabNameText = value; base.RaisePropertyChanged(); }
        }

        private ObservableCollection<ViewTableEntity> _viewTables = new ObservableCollection<ViewTableEntity>();

        public ObservableCollection<ViewTableEntity> ViewTables {
            get { return _viewTables; }
            set { _viewTables = value; base.RaisePropertyChanged(); }
        }

        private ViewTableEntity _selectViewTable;

        public ViewTableEntity SelectViewTable {
            get { return _selectViewTable; }
            set { _selectViewTable = value; base.RaisePropertyChanged(); }
        }


        private ObservableCollection<ViewTableDtlEntity> _viewTableDtls = new ObservableCollection<ViewTableDtlEntity>();

        public ObservableCollection<ViewTableDtlEntity> ViewTableDtls {
            get { return _viewTableDtls; }
            set { _viewTableDtls = value; base.RaisePropertyChanged(); }
        }

        public DelegateCommand SearchViewTableCommand => new DelegateCommand(() => {
            LoadViewTableData();
        });

        public DelegateCommand AddViewTableCommand => new DelegateCommand(() => {
            DialogParameters keyValuePairs = new DialogParameters();
            keyValuePairs.Add("Title", "新增对照表");
            _dialog.ShowDialog(nameof(EditViewTableDialogView), keyValuePairs, (rhs) => {
                if (rhs.Result == ButtonResult.OK) {
                    LoadViewTableData();
                }
            });
        });

        public DelegateCommand EditViewTableCommand => new DelegateCommand(() => {
            DialogParameters keyValuePairs = new DialogParameters();
            keyValuePairs.Add("Title", "编辑对照表");
            keyValuePairs.Add("ViewTableEntity", JsonConvert.SerializeObject(SelectViewTable));
            _dialog.ShowDialog(nameof(EditViewTableDialogView), keyValuePairs, (rhs) => {
                if (rhs.Result == ButtonResult.OK) {
                    LoadViewTableData();
                }
            });
        });

        public DelegateCommand<ViewTableEntity> ViewTableSelectionChangedCommand => new DelegateCommand<ViewTableEntity>((rhs) => {
            LoadViewTableDtlData();
        });

        public DelegateCommand<ViewTableEntity> DelViewTableDtlCommand => new DelegateCommand<ViewTableEntity>((rhs) => {
            if (rhs != null) {
                var ask = _message.Ask("确认是否删除此对照表，以及该对照表下的所有数据？");
                if (ask == System.Windows.MessageBoxResult.OK) {
                    _mainDbOperate.DeleteModel<ViewTableEntity>(o => o.Id == rhs.Id);
                    _mainDbOperate.DeleteModel<ViewTableDtlEntity>(o => o.ViewTabeID == rhs.Id);
                    LoadViewTableData();
                }
            }
        });
        

        public DelegateCommand AddViewTableDtlCommand => new DelegateCommand(() => {
            if (SelectViewTable == null || SelectViewTable.Id  == 0) {
                _message.Error("请选择一项左侧的对照表后再添加！");
                return;
            }
            ViewTableDtls.Add(new ViewTableDtlEntity() { ViewTabeID = SelectViewTable.Id });
        });

        public DelegateCommand SaveViewTableDtlCommand => new DelegateCommand(() => {
            var list = ViewTableDtls.Where(o => o.Id == 0).ToList();
            if (list.Count > 0) {
                _mainDbOperate.AddModels(list);
                LoadViewTableDtlData();
            } else {
                _mainDbOperate.GetFreeSql().InsertOrUpdate<ViewTableDtlEntity>().SetSource(ViewTableDtls.ToList()).ExecuteAffrows();
            }
        });


        protected override void OnViewLoaded() {
            LoadViewTableData();
            LoadViewTableDtlData();
            //base.OnViewLoaded();
        }


        private void LoadViewTableData() {
            var list = _mainDbOperate.GetFreeSql()
                .Queryable<ViewTableEntity>()
                .WhereIf(!string.IsNullOrEmpty(SearchViewTabNameText),o=>o.ViewTableName.Contains(SearchViewTabNameText))
                .ToList();
            ViewTables.Clear();
            ViewTables.AddRange(list);
            if (list.Count > 0) {
                SelectViewTable = list.First();
            }
        }

        private void LoadViewTableDtlData() {
            if (SelectViewTable != null) {
                var list = _mainDbOperate.GetFreeSql()
                       .Queryable<ViewTableDtlEntity>()
                       .Where(o => o.ViewTabeID == SelectViewTable.Id)
                       .ToList();
                ViewTableDtls.Clear();
                ViewTableDtls.AddRange(list);
            }
        }

    }

}
